package com.kingschan.util.excel.jxl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kingschan.util.lang.StringUtil;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
 * Excel操作工具类
 * @author kingschan
 *date:2013-4-18
 */
public class ExcelOutput {
	//private static Logger log = Logger.getLogger(ExcelOutput.class);
	
	/**
	 * 将List导出为excel文件
	 * @param titles 中文表头
	 * @param rtList 列表内容
	 * @return InputStream 用于存放excel文件数据的输入流。
	 */
	
	public InputStream exportExcel(String[] titles,List<?> rtList){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		WritableWorkbook workbook;   
        try {   
            workbook = Workbook.createWorkbook(baos);            
            WritableSheet sheet = workbook.createSheet("Sheet1", 0);   
            //写数据
            //第一行写中文表头字段
            setHead(titles,sheet);
            if(rtList!=null && rtList.size()>0){
            	//第二行（行号为1）开始写内容
        		int row = 1;
        		for(int i = 0 ;i<rtList.size();i++){
        			Object[] values = (Object[]) rtList.get(i);
        			for(int j = 0;j<values.length;j++){ 
        				String value = StringUtil.ConvertNullStr(values[j]);
        				try {
        					jxl.write.Number labelN = new jxl.write.Number(j, row, Double.parseDouble(value.trim()));
        					sheet.addCell(labelN); 
						} catch (Exception e) {
							Label label = new Label(j, row,value); 
            				sheet.addCell(label); 
						}
        			}
        			row++;//写完一行，到下一行
        		}
            }
            workbook.write();   
            workbook.close();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
        InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
        return inputStream;
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("-?[0-9]*.?[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 导出数据excel文件，excel第一行写入表头中文名称
	 * @param sheet
	 * @param exportFs
	 */
	public void setHead( String[] titles ,WritableSheet sheet) {
		if(titles==null)return;
		for(int i = 0 ;i<titles.length;i++){ 
			String title = titles[i];
			Label label = new Label(i,0,title);   
	        try {
				sheet.addCell(label);
			} catch (Exception e) {
				e.printStackTrace();
			}  
		}
	}







	
	
	
	
	
	
}
